/**
 * step 3 广告创意 & 名称配置
 */
define(['../../common/service',  './createAdUtils', '../../plugins/pretag'],
    function(http, adUtils) {
        var Step3 = {
            //titleObj:{},
            init: function() {
                var _this = this;
                _this.init_homepage();
                //行动号召
                _this.init_activeSelect();
                _this.init_event();
                _this.init_rich_text('dpaTitle');
                _this.init_rich_text('dpaAdword');
                _this.init_rich_text('dynamicMsgLinkDesc');
                _this.init_all_tags();
                //初始化 追踪参数
                $("input[name=linkParam]").val(window.localStorage.getItem("linkParam"));
                //初始化推广网址
                $("input[name=link]").val($("div.ndp-drop-wrapper[name=feed-drop]").data("data").promotedWebsite ? $("div.ndp-drop-wrapper[name=feed-drop]").data("data").promotedWebsite : "");
            },
            init_homepage: function() {
                var _this = this;
                http.do('/createAd/getAllApps ', null, 'POST').then(function(res) {
                    if (res.flag == 'fail') {
                        Kit.alert2(res.errorMsg);
                        return;
                    }
                    $("#originality select[name=homepage-select2]").empty().select2({
                        data: $.map(res.data, function(item) {
                            item.id = item.fbPageId;
                            item.text = item.text || item.name;
                            return item;
                        }),
                        templateResult: _this.homePage_formatState,
                        templateSelection: _this.homePage_formatState,
                        escapeMarkup: function(m) {
                            return m;
                        }
                    }).on("select2:select", function(e) {}).select2("val", adUtils.pageId);
                });
            },
            homePage_formatState: function formatState(state) {
                if (!state.pictureUrl) {
                    state.pictureUrl = '';
                }
                var $state = $(
                    '<span><img src="' + state.pictureUrl + '" class="img-flag" width="20" height="20" /> ' + state.text + '</span>');
                return $state;
            },
            init_activeSelect: function() {
                $("div.ndp-drop-wrapper[name=originality-drop]").off("ITEM_CLICK").empty().drop({
                    caret: "glyphicon-menu-right",
                    data: [{
                        text: I18N.getText('createAd', 'noButton'),
                        value: "NO_BUTTON",
                        disabled: true
                    }, {
                        text: I18N.getText('createAd', 'bookNow'),
                        value: "BOOK_TRAVEL"
                    }, {
                        text: I18N.getText('createAd', 'download'),
                        value: "DOWNLOAD",
                        id: 6
                    }, {
                        text: I18N.getText('createAd', 'learnMore'),
                        value: "LEARN_MORE"
                    }, {
                        text: I18N.getText('createAd', 'openLink'),
                        value: "OPEN_LINK"
                    }, {
                        text: I18N.getText('createAd', 'shopNow'),
                        value: "SHOP_NOW",
                        id: 1
                    }, {
                        text: I18N.getText('createAd', 'signUp'),
                        value: "SIGN_UP",
                        id: 5
                    }],
                    name: "originality" //为了方便serialize 建议设置name 属性
                }).on("ITEM_CLICK", function(e) { //下拉选择项点击事件
                }).val(I18N.getText('createAd', 'shopNow'));
                $("input[name=originality]").attr('data-val', 'SHOP_NOW');
            },
            init_event: function() {
                var _this = this;
                //创意形式
                $('input[name="pic"]').off("click").on("click", function(e) {
                    var v = $(this).val();
                    if (v == "carousel") {
                        $(".or-style label[for=video-ad-extend]").show();
                        $("#video-ad-extend").prop("checked", "checked");
                        $("div.linkCaption-show-div").removeClass("hidden");
                        ////显示默认的显示网址
                        //var linkCaption = $("div.ndp-drop-wrapper[name=product-drop]").data("data").webSite ?
                        //    $("div.ndp-drop-wrapper[name=product-drop]").data("data").webSite : "";
                        //linkCaption = linkCaption.replace("http://", "").replace("https://", "");
                        //$("div.linkCaption-show-div").find('input[name="linkCaption"]').val(
                        //    linkCaption);
                    } else {
                        $("#video-ad-extend").removeAttr("checked");
                        $("input[name=linkCaption]").val("");
                        $(".or-style label[for=video-ad-extend]").hide();
                        $("div.linkCaption-show-div").addClass("hidden");
                    }
                });
                //默认单图
                $('input[name="pic"][value="carousel"]').trigger("click");

                //选择创意
                $("#originality .img li").click(function() {
                    _this.init_Dialog();
                });
                //清除创意
                $("#originality .img li").eq(0).show();
                $("#originality .img li").eq(1).find(".thumbnail").empty();
                $("#originality .img li").eq(1).hide();
                //清除显示网站的值
                $("input[name=linkCaption]").val("");

                //导入广告语
                $("button.import-ad-btn").unbind('click').bind('click', function() {
                    _this.importAdword();
                });
                //save adword
                $("button.save-ad-btn").unbind('click').bind('click', function() {
                    _this.saveAdword();
                });
                //预算输入校验
                $("input.budget-input").bind('keypress', function(evt) {
                    var char = String.fromCharCode(evt.keyCode);
                    // 如果不是数字，就不允许输入
                    if (!/\d/.test(char)) {
                        if (char != ".") {
                            evt.preventDefault();
                        }
                    }
                });
                //预算必须大于 5
                $("input.budget-input").bind('focusout', function(evt) {
                    var optimizingVal = $('[name=optimizing-drop] input').data('val'); //优化方式
                    var chargeVal = $('[name=charge-drop] input').data('val'); //优化方式
                    if ((optimizingVal == chargeVal) && (optimizingVal == 'LINK_CLICKS')) {
                        if (Number($(this).val()) < 5) {
                            Kit.alert3(I18N.getText("createAd","dailyBudgetMinLimit",5));
                        }
                    }
                });
                $("input.price-input").bind('keypress', function(evt) {
                    var char = String.fromCharCode(evt.keyCode);
                    // 如果不是数字，就不允许输入
                    if (!/\d/.test(char)) {
                        if (char != ".") {
                            evt.preventDefault();
                        }
                    }
                });
                //单价必须大于 0.01
                $("input.price-input").bind('focusout', function() {
                    if (Number($(this).val()) < 0.01) {
                        Kit.alert3(I18N.getText("createAd","dailyBudgetMinLimit",0.01));
                    }
                });
            },
            init_Dialog: function() {
                var _this = this;
                $("#choose-originality-dialog").modal({
                    backdrop: 'static',
                    keyboard: false
                });
                //获取创意模板数据
                http.do('/ecTemplateMateriel/findByFeed ', {
                    feedId: adUtils.publishParamCache.weFeedId
                }, 'POST').then(function(res) {
                    if (res.flag == 'fail') {
                        Kit.alert2(res.errorMsg);
                        return;
                    }
                    var _html = "";
                    $.each(res.data, function(i, obj) {
                        _html += '<div class="col-sm-6 col-md-3"><div class="thumbnail">';
                        _html += '<img data-templateId="' + obj.id +
                            '" data-src="' + obj.thumbnail + '" alt="" src="' + obj.thumbnail + '"><div class="caption">';
                        _html += '<h5 title="' + obj.name + '">' + obj.name + '</h5></div></div></div>';
                        //_html += '<p><a href="#" class="btn btn-default" role="button">预览</a></p>' 预览功能先去掉了
                    });
                    $("#choose-originality-dialog .modal-body .row").empty().append(_html);
                    _this.choose_picture();
                });
            },
            _closeDialog: function($dom) {
                $dom.modal('hide');
            },
            choose_picture: function() {
                    var _this = this;
                    $("#choose-originality-dialog .thumbnail").click(function() {
                        //获取所选模板的图片和value，close the dialog
                        var templateId = $(this).find("img").attr("data-templateId");
                        var _html = '<img data-templateId="' + templateId + '" ' +
                            '+ data-src="' + $(this).find("img").data("src") + '" src="' + $(this).find("img").data("src") + '">';
                        $("#originality .img li").eq(0).hide();
                        $("#originality .img li").eq(1).find(".thumbnail").empty().append(_html);
                        $("#originality .img li").eq(1).show();
                        _this._closeDialog($("#choose-originality-dialog"));
                    });
                }
                /**
                 * 初始化标题
                 */
                ,
            init_rich_text: function(name) {
                var _this = this;
                adUtils.fieldObj[name] = $("div[name='" + name + "']").empty().field();
                var tagName = name + '-tags';
                $("div[name='" + name + "']").focus(function() {
                    $("div[name='" + tagName + "']").show();
                });

                $("div[name='" + name + "']").focusout(function(e) {
                    $("div[name='" + tagName + "']").hide();
                });
            },
            init_all_tags: function() {
                var _this = this;
                http.work('/ec/tags', 'POST').then(function(d) {
                    if (d.flag == 'fail') {
                        Kit.alert2(d.errorMsg);
                        return;
                    }
                    var tags = {
                        tagNames: d.data,
                        tagVals: []
                    }
                    if (window.localStorage.getItem("adGroupSeq") != null) {
                        tags['adGroupSeq'] = JSON.parse(window.localStorage.getItem("adGroupSeq"));
                    }
                    if (window.localStorage.getItem("adSetSeq") != null) {
                        tags['adSetSeq'] = JSON.parse(window.localStorage.getItem("adSetSeq"));
                    }
                    if (window.localStorage.getItem("adCampSeq") != null) {
                        tags['adCampSeq'] = JSON.parse(window.localStorage.getItem("adCampSeq"));
                    }
                    superInput.init(tags);
                    //初始化标题，广告语，动态链接描述的tags
                    _this.init_rich_tags(d.data, 'dpaTitle');
                    _this.init_rich_tags(d.data, 'dpaAdword');
                    _this.init_rich_tags(d.data, 'dynamicMsgLinkDesc');
                });
            },
            init_rich_tags: function(tags, name) {
                    var _this = this;
                    var temp = [];
                    $.each(tags, function(i, obj) {
                        if (name == 'dpaTitle' && obj.supportDpaTitle == 1) {
                            temp.push(obj);
                        } else if (name == 'dpaAdword' && obj.supportDpaAdword == 1) {
                            temp.push(obj);
                        } else if (name == 'dynamicMsgLinkDesc' && obj.supportDpaDynamicMsg == 1) {
                            temp.push(obj);
                        }
                    });
                    var html = "",
                        tagName = name + "-tags";
                    $.each(temp, function(i, o) {
                        html += "<button class='tags-element' data-val='" + o.tag + "'>";
                        html += o.name + "</button>";
                    });
                    $("div[name='" + tagName + "']").empty().append(html);
                    //绑定按钮事件
                    $("div[name='" + tagName + "']").find('button').click(function() {
                        var obj = {
                            val: $(this).attr('data-val'),
                            text: $(this).text()
                        }
                        adUtils.fieldObj[name].addTag(obj);
                    });
                    $("button.tags-element[data-val]").mousedown(function(e) {
                        e.preventDefault();
                    });
                }
                /***************************  以下是广告语管理功能  *****************************************/
                /**
                 * 导入广告词
                 */
                ,
            importAdword: function() {
                    var _this = this;
                    $("#import-adwords-dialog").modal({
                        backdrop: 'static',
                        keyboard: false
                    });
                    //初始化select and table
                    http.do('/ec/allWebSite ', null, 'GET').then(function(res) {
                        if (res.flag == 'fail') {
                            Kit.alert2(res.errorMsg);
                            return;
                        }
                        var appsData = [];
                        $.each(res.data, function(i, obj) {
                            //处理渲染的数据
                            var tempObj = {};
                            tempObj.id = obj.productManageProductId;
                            tempObj.text = obj.companyName;
                            appsData.push(tempObj);
                        });
                        $("div.ndp-drop-wrapper[name=adword-product-drop]").off("ITEM_CLICK").empty().drop({
                            caret: "glyphicon-menu-right",
                            data: appsData,
                            name: "adwordsProduct" //为了方便serialize 建议设置name 属性
                        }).on("ITEM_CLICK", function(e) { //下拉选择项点击事件
                            //初始化feed,account
                        });
                        $('div[name=adword-product-drop] .drop-list .drop-one-item[value="' + adUtils.publishParamCache.productId + '"]').trigger('click');
                    });
                    _this.searchLanguage($("div.ndp-drop-wrapper[name=adword-language-drop ]"), 'adwordsLanguage');
                    var param = {
                        productId: adUtils.publishParamCache.productId
                    };
                    _this.searchWords(param);
                    _this.init_import_dialag_event();
                }
                /**
                 * save 广告词
                 */
                ,
            saveAdword: function() {
                var _this = this;
                var words = adUtils.fieldObj.dpaAdword.getContent();
                if (Kit.isBlank(words)) {
                    Kit.alert2(I18N.getText("adwords","inputAdword"));
                    return;
                }
                $("#save-adwords-dialog").modal({
                    backdrop: 'static',
                    keyboard: false
                });
                _this.searchLanguage($("div.ndp-drop-wrapper[name=adword-save-language-drop]"), 'adwordSaveLanguage');
                _this.init_save_dialag_event();
            },
            searchWords: function(param) {
                $("#import-adwords-dialog table").find("tbody").empty();
                http.work('/adwords/getAdwordsAllList', param, 'GET').then(function(d) {
                    if (d.flag == 'fail') {
                        Kit.alert2(d.errorMsg);
                        return;
                    }
                    var da = d.data;
                    var html = '';
                    if (da.length == 0) {
                        $("#import-adwords-dialog table").find("tbody").append("<tr><td style='background-color: white;text-align: center;' " +
                            "colspan='3'>"+ I18N.getText("createAd","noAdwordData") +"</td></tr>");
                    } else {
                        for (var i = 0; i < da.length; i++) {
                            //$("#import-adwords-dialog table").find("input[no="+ i +"]").data('val',da[i].word);
                            var superInputHtml = da[i].word.replaceAll("#b#n", " ");
                            superInputHtml = superInputHtml.replace(/\{\{(.+?)\}\}/g,
                                function(t) {
                                    t = t.replace('{{', '').replace('}}', '');
                                    var arr = t.split('|');
                                    return '<span class="deco-tag">' + arr[1] + '</span>';
                                })
                            html += '<tr><td class="text-center" width="50px">' +
                                '<input no=' + JSON.stringify(da[i].word) + ' type="radio" name="adword-select-radio"></td>' +
                                '<td class="text-center" width="80px">' + (i + 1) + '</td>' +
                                '<td><div class="select-tags adword">' + superInputHtml +
                                '</div><div class="remark">' + (da[i].description || '') + '</div></td></tr>';
                        }
                        $("#import-adwords-dialog table").find("tbody").append(html);
                    }
                });
            },
            init_import_dialag_event: function() {
                var _this = this;
                //用户点击搜索按钮
                $("button.adword-search").unbind("click").click(function() {
                    var param = {
                        productId: $("input[name=adwordsProduct]").attr('data-val')
                    };
                    var languageId = $("input[name=adwordsLanguage]").attr('data-val');
                    if (languageId != -1) {
                        param.languageId = languageId;
                    }
                    _this.searchWords(param);
                });
                $("button.adwords-import-btn").unbind("click").click(function() {
                    var data = $("input[name=adword-select-radio]:checked").attr("no");
                    if (data != null) {
                        //填充tag
                        $('div[name="dpaAdword"]').empty();
                        adUtils.fieldObj.dpaAdword.fill(data);
                        //superInput.dataFill('dpaAdwordSeq',data);
                    }
                    _this._closeDialog($("#import-adwords-dialog"));
                });
            },
            init_save_dialag_event: function() {
                var _this = this;
                $("button.adwords-save-btn").unbind("click").click(function() {
                    var values = adUtils.fieldObj.dpaAdword.getContent();
                    if (Kit.isBlank(values)) {
                        Kit.alert2(I18N.getText("adwords","inputAdword"));
                        return;
                    }
                    var lan = $('#save-adwords-dialog input[name=adwordSaveLanguage]').attr('data-val');
                    if (lan == -1) {
                        Kit.alert2(I18N.getText("adwords","selectLanguage"));
                        return;
                    }
                    var param = {
                        "productId": adUtils.publishParamCache.productId,
                        "languageId": lan,
                        "word": values,
                        "description": $('#save-adwords-dialog textarea[name=save-des]').val() || ''
                    }
                    http.work('/adwords/createAdword', param, 'POST').then(function(d) {
                        if (d.flag == 'fail') {
                            Kit.alert2(res.errorMsg);
                            return;
                        }
                        _this._closeDialog($("#save-adwords-dialog"));
                        Kit.alert_success(I18N.getText("createAd","saveSuccess"));
                    });

                });
            },
            searchLanguage: function($dom, name) {
                var _this = this;
                var par = {
                    "type": "adword"
                };
                http.do("/search/getDictionary", {
                    param: JSON.stringify(par)
                }).then(function(res) {
                    var appsData = [];
                    $.each(res.data, function(i, obj) {
                        //处理渲染的数据
                        var tempObj = {};
                        tempObj.id = obj.id;
                        tempObj.text = obj.name;
                        appsData.push(tempObj);
                    });
                    $dom.off("ITEM_CLICK").empty().drop({
                        caret: "glyphicon-menu-right",
                        data: appsData,
                        name: name
                    }).on("ITEM_CLICK", function(e) { //下拉选择项点击事件
                        //初始化feed,account
                    }).val(I18N.getText("adwords","selectLanguage"));
                    $("input[name=" + name + "]").attr('data-val', -1);
                }, function() {
                    Kit.alert2(I18N.getText('createAdword', 'createFail'));
                });
            }
        }
        return Step3;
    });
